import cv2
import numpy as np

def get_onelastkiss(img_name, input_path, temp_path, output_path):

    if img_name.endswith(".jpg"):
        line_name = temp_path + str(img_name).replace('.jpg', '_line.jpg').replace(input_path, '')
        gradient_name = temp_path + str(img_name).replace('.jpg', '_gradient.jpg').replace(input_path, '')
        save_name = output_path + str(img_name).replace('.jpg', '_onelastkiss.jpg').replace(input_path, '')
    if img_name.endswith(".png"):
        line_name = temp_path + str(img_name).replace('.png', '_line.jpg').replace(input_path, '')
        gradient_name = temp_path + str(img_name).replace('.png', '_gradient.jpg').replace(input_path, '')
        save_name = output_path + str(img_name).replace('.png', '_onelastkiss.jpg').replace(input_path, '')

    line = cv2.imread(line_name)
    gradient = cv2.imread(gradient_name)

    height, width, n = line.shape  

    onelastkiss = np.zeros((height, width, n), dtype='uint8')
    onelastkiss.fill(255)

    mean = cv2.mean(line)
  
    for i in range(0, height):
        for j in range(0, width):
            if line[i][j][0] < mean[0]:
                onelastkiss[i][j] = gradient[i][j]

    cv2.imwrite(save_name, onelastkiss)

def get_half_onelast(img_name, input_path, temp_path, output_path):

    img = cv2.imread(img_name)
    one_name = str(img_name).replace(input_path, output_path).replace('.jpg', '_onelastkiss.jpg')
    one = cv2.imread(one_name)
    height, width, n = img.shape

    if img_name.endswith(".jpg"):
        save_name = output_path + str(img_name).replace('.jpg', '_halfonelastkiss.jpg').replace(input_path, '')
    if img_name.endswith(".png"):
        save_name = output_path + str(img_name).replace('.png', '_halfonelastkiss.jpg').replace(input_path, '')

    height, width, n = img.shape  

    halfone = np.zeros((height, width, n), dtype='uint8')
    halfone.fill(255)  

    if height < width:
        
        top_start = round(width * (1 - 0.618))
        bottom_start = round(width * 0.618)

        k = (top_start - bottom_start) / height

        for i in range(0, height):
            for j in range(0, width):
                if j > i * k + bottom_start:
                    halfone[i][j] = img[i][j]
                else:
                    halfone[i][j] = one[i][j]
    
    else :
        left_start = round(height * (1 - 0.618))
        right_start = round(height * 0.618)

        k = (left_start - right_start) / width

        for i in range(0, height):
            for j in range(0, width):
                if i < j * k + right_start:
                    halfone[i][j] = img[i][j]
                else:
                    halfone[i][j] = one[i][j]

    cv2.imwrite(save_name, halfone)
